<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Grid\ClueFileUploadAction;
use App\Admin\Actions\Grid\DispatchClueBatchAction;
use App\Admin\Forms\ClueArchiveForm;
use App\Admin\Grid\Tools\ImportClueToolButton;
use App\Admin\Metrics\Examples\MyCard;
use App\Admin\Renderable\DispatchUser;
use App\Admin\Renderable\DispatchUserTable;
use App\Admin\Renderable\SetClueTagForm;
use App\Admin\Renderable\UserTable;
use App\Models\Administrator;
use App\Models\Clue;
use App\Models\MediaSource;
use App\Models\Tag;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Layout\Column;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Layout\Row;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Widgets\Card;
use Illuminate\Support\Facades\DB;

class ClueController extends AdminController
{

    protected $title = '全部线索';
    protected $isUserClues = false;

    public function index(Content $content)
    {
        $url = request()->url();
        $this->isUserClues = str_contains($url, "clues/user");
//        $this->isUserClues = !Admin::user()->inRoles(['operator' , 'user_manager']);
        if ($this->isUserClues)
            $this->title = '我的线索';
        elseif (!Admin::user()->inRoles(['operator', 'user_manager', 'administrator'])) {
            return redirect(admin_route('admin.clue.user'));
        }

        return $content
            ->translation($this->translation())
            ->title($this->title())
            ->description($this->description()['index'] ?? trans('admin.list'))
            ->body($this->grid());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Clue(), function (Grid $grid) {
            $model = $grid->model()
                ->select([
                    'id',
                    'a_status',
                    'crm_status',
                    'post_date',
                    'user_id',
                    'tag_id',
                    'name',
                    'phone',
                    'source',
                    'ad_name',
                    'site_name',
                    'url',
                    'question_data',
                    'location',
                    'ip',
                    'dispatch_date',
                    'remark',
                    'rule_id',
                    'no_dispatch',
                    'files',
                ])
                ->with(['user', 'rule', 'tag'])
                ->orderBy("post_date", 'desc');

            $user = Admin::user();
            $hideFields = collect(json_decode(admin_setting('hide_fields'), true));
            $managerUserId = null;
            $enableTag = admin_setting('enable_clue_tags', false);
            $enableFiles = admin_setting('enable_files', false);
            if (!$user->isAdministrator()) {
                if ($user->isRole('user_manager')) {
                    $managerUserId = Administrator::getManagerChildren($user->departments(), true)
                        ->unique()
                        ->toArray();
                }
            }
            if ($managerUserId) {
                $model->addQuery('whereIn', [
                    'user_id',
                    $managerUserId
                ]);
            }

            if ($this->isUserClues) {
                $grid->setResource("/clues");

                $grid->model()
                    ->addQuery('where', ['user_id', $user->id]);
            }
            $canDispatch = $user->can('clues.dispatch');
            if ($canDispatch) {
                $grid->batchActions([new DispatchClueBatchAction($managerUserId)]);
                if (!$user->isRole('user_manager'))
                    $grid->header(function () use ($grid) {
                        $unDispatchCount = Clue::query()
                            ->select(['user_id', 'no_dispatch', DB::raw('count(*) as count')])
                            ->whereNull('user_id')
                            ->groupBy('no_dispatch')
                            ->get();
                        $total = $unDispatchCount->sum('count');
                        if (!$total) return '';

                        $row = new Row();

                        $row->column(1 / 3, function (Column $column) use ($total, $unDispatchCount) {
                            $unDispatchCount = $unDispatchCount->pluck('count', 'no_dispatch');

                            $card = new MyCard("未分配数量");
                            $card->appendHtmlAttribute('style', "margin-bottom:0px;margin-top:15px;");
                            $aUrl = admin_route('admin.clues', [
                                '_user_id' => '1',
                            ]);
                            $bUrl = admin_route('admin.clues', [
                                '_user_id' => '1',
                                'no_dispatch' => '1',
                            ]);
                            $cUrl = admin_route('admin.clues', [
                                '_user_id' => '1',
                                'no_dispatch' => '0',
                            ]);

                            $card->content("<a href='$aUrl'>$total</a>");
                            $footerStr = [];
                            if ($a1 = $unDispatchCount->get(0)) {
                                $footerStr[] = "普通线索: <a href='$cUrl'>$a1</a>";
                            }
                            if ($a2 = $unDispatchCount->get(1)) {
                                $footerStr[] = "飞鱼智能电话: <a href='$bUrl'>$a2</a>";
                            }

                            $card->footer(implode('<br/>', $footerStr));
                            $column->row($card);
                        });
                        return $row;
                    });
            }
            if ($this->isUserClues) {
                $grid->header(function () use ($user, $enableTag) {

                    $row = new Row();
                    if ($noteMsg = admin_setting('note_plan')) {
                        $row->column(3 / 4, function (Column $column) use ($noteMsg) {
                            $card = new MyCard(admin_setting('note_plan_title', '留言板'));
                            $card->appendHtmlAttribute('style', "margin-bottom:0px;margin-top:15px;");
                            $card->content("$noteMsg");
                            $column->row($card);
                        });

                    }
                    if ($enableTag) {
                        $count = Clue::query()
                            ->select(['tag_id', 'user_id'])
                            ->where('user_id', $user->id)
                            ->whereNull('tag_id')
                            ->count();
                        if ($count)
                            $row->column(1 / 4, function (Column $column) use ($count) {
                                $card = new MyCard("未添加标签数量");
                                $card->appendHtmlAttribute('style', "margin-bottom:0px;margin-top:15px;");

                                $bUrl = admin_route('admin.clue.user', [
                                    '_tag_id' => '1',
                                ]);
                                $card->content("<a href='$bUrl'>$count</a>");

                                $totalPrice = $count * 20;
                                $card->footer("预估罚款金额: <strong style='color:red;font-size:18px'>{$totalPrice}</strong>元");
                                $column->row($card);
                            });
                    }
                    return $row;
                });
            }

            if (\Admin::user()->can('clue.import'))
                $grid->tools([new ImportClueToolButton()]);

            $grid->rows(function ($rows) {
                foreach ($rows as $row) {
                    if ($row->a_status === Clue::A_STATUS_UN_ACTION && in_array($row->crm_status, [Clue::CRM_STATUS_UN_CHECK, Clue::CRM_STATUS_UN_ARCHIVE])) {
                        $row->setAttributes(['style' => 'background: rgba(176,189,108,.3)']);
                    } else if ($row->a_status === Clue::A_STATUS_ARCHIVE_ERROR) {
                        $row->setAttributes(['style' => 'background: rgba(255,46,46,.6)']);
                    } else if ($row->a_status === Clue::A_STATUS_ARCHIVE_REPEAT || $row->crm_status === Clue::CRM_STATUS_REPEAT) {
                        $row->setAttributes(['style' => 'background: rgba(221,221,221,.3)']);
                    }
                }
            });

            $grid->disableCreateButton();
            $grid->disableViewButton();
            $grid->disableEditButton();
            $grid->disableQuickEditButton();
            if (!$user->isAdministrator()) {
                $grid->disableDeleteButton();
                $grid->disableBatchDelete();
            }
            $MediaSourceOptions = MediaSource::toOptions();
            if ($user->can('clue.export')) {
                $grid->export()->rows(function ($rows) use ($MediaSourceOptions) {
                    foreach ($rows as $index => &$row) {
                        $row['source'] = data_get($MediaSourceOptions, $row['source']);
                        $row['user_id'] = data_get($row, 'user.name');
                        if ($row['a_status'] === Clue::A_STATUS_UN_ACTION && in_array($row['crm_status'], [Clue::CRM_STATUS_UN_CHECK, Clue::CRM_STATUS_UN_ARCHIVE])) {
                            $row['_a_status'] = '未建档';
                        } else {
                            $row['_a_status'] = data_get(Clue::A_STATUS_OPTIONS, $row['a_status'], data_get(Clue::CRM_STATUS_OPTIONS, $row['crm_status']));
                        }
                    }

                    return $rows;
                });
            }

            $grid->showColumnSelector();
            $headFix = 6;
            if ($enableTag) $headFix++;
            if ($canDispatch) $headFix++;
            $hiddenSource = !($this->isUserClues && $hideFields->contains('source'));
            if ($hiddenSource) $headFix = $headFix - 2;
            $grid->fixColumns($headFix, 0);

            $grid->column('id')->display(function () {
                return $this->_index + 1;
            });
            if ($canDispatch)
                $grid->column('user_id')
                    ->display(function () {
                        return data_get($this->user, 'name', '-未-');
                    })
                    ->superModal(function ($d) use ($managerUserId) {
                        $d->icon('');
                        $id = data_get($this->user, 'id');

                        return DispatchUser::make()->payload([
                            '_users' => $managerUserId,
                            'id' => $this->id,
                            'user_id' => $id,
                        ]);
                    });

            if ($enableTag)
                $grid->column('tag_id')
                    ->display(function () {
                        return data_get($this->tag, 'name', '未标注');
                    })
                    ->label()
                    ->superModal(function ($d) {
                        $d->icon('');
                        $id = data_get($this->tag, 'id');

                        return SetClueTagForm::make()->payload([
                            'id' => $this->id,
                            'tag_id' => $id,
                        ]);
                    });

            $grid->column('name');
            $grid->column('phone')
                ->copyable();

            if ($hiddenSource) {
                $grid->column('source')
                    ->using($MediaSourceOptions)
                    ->label();
            }
            if (!($this->isUserClues && $hideFields->contains('post_date')))
                $grid->column('post_date');

            if (!($this->isUserClues && $hideFields->contains('site_name')))
                $grid->column('site_name');
            if (!($this->isUserClues && $hideFields->contains('ad_name')))
                $grid->column('ad_name');
            if (!($this->isUserClues && $hideFields->contains('url')))
                $grid->column('url')->limit(50)->hide();
            if ($hiddenSource) {
                $grid->column('rule_id')->display(function () {
                    return data_get($this, 'rule.name', '!未匹配规则!');
                })->hide();
            }

            if (!($this->isUserClues && $hideFields->contains('ip')))
                $grid->column('ip');
            if (!($this->isUserClues && $hideFields->contains('location')))
                $grid->column('location');
            if (!($this->isUserClues && $hideFields->contains('question_data')))
                $grid->column('question_data')
                    ->view('admin.fields.json');

            $grid->column('_a_status', '建档状态')
                ->display(function () {
                    if ($this->a_status)
                        return data_get(Clue::A_STATUS_OPTIONS, $this->a_status);
                    return data_get(Clue::CRM_STATUS_OPTIONS, $this->crm_status);
                })
                ->if(function () use ($user) {
                    if ($user->isAdministrator() || $this->a_status === Clue::A_STATUS_ARCHIVE_ERROR)
                        return true;

                    if (in_array($this->a_status, [Clue::A_STATUS_UN_ACTION, Clue::A_STATUS_ARCHIVE_REPEAT])) {
                        return in_array($this->crm_status, [Clue::CRM_STATUS_UN_CHECK, Clue::CRM_STATUS_UN_ARCHIVE, Clue::CRM_STATUS_REPEAT]);
                    }
                    return false;
                })
                ->superModal(function ($d) {
                    $d->icon('');
                    $payload = $this->toArray();
                    return ClueArchiveForm::make()->payload($payload);
                });

            if ($canDispatch)
                $grid->column('dispatch_date');

            $remark = $grid->column('remark', '备注')
                ->style('min-width:150px;');
            if ($user->can('clues.add_remark'))
                $remark->newEditable();
            if ($enableFiles) {
                if ($user->can('clues.file_manager'))
                    $grid->actions([new ClueFileUploadAction()]);
                $grid->column('files', '附件')->newAudio();
            }

            $grid->quickSearch(['name', 'phone']);
            $grid->filter(function (Grid\Filter $filter) use ($managerUserId, $MediaSourceOptions, $enableTag) {
                $filter->equal('id');
                $filter->like('name');
                $filter->like('phone');
                $filter->like('ad_name');
                $filter->like('site_name');
                $filter->in('source')->multipleSelect($MediaSourceOptions);
                if ($enableTag) {
                    $filter->in('tag_id')
                        ->multipleSelect(Tag::toOptions());
                    $filter->where('_tag_id', function ($query) {
                        switch ($this->input) {
                            case "1":
                                $query->whereNull('tag_id');
                                break;
                        }
                    }, '标签筛选')
                        ->radio([
                            '1' => '未标注',
                        ]);
                }

                $filter->where('_user_id', function ($query) {
                    switch ($this->input) {
                        case "1":
                            $query->whereNull('user_id');
                            break;
                        case "2" :
                            $query->whereNotNull('user_id');
                            break;
                    }
                }, '分配筛选')
                    ->radio([
                        '1' => '未分配',
                        '2' => '已分配'
                    ]);

                $filter->equal('no_dispatch', '飞鱼智能电话')
                    ->radio([
                        '1' => '是',
                        '0' => '否'
                    ]);
                $filter->where('a_status', function ($query) {
                    $val = $this->input;
                    switch ($val) {
                        case "1":
                            $query->where('a_status', Clue::A_STATUS_UN_ACTION)
                                ->whereIn('crm_status', [Clue::CRM_STATUS_UN_CHECK, Clue::CRM_STATUS_UN_ARCHIVE]);
                            break;
                        case "2":
                            $query->where('a_status', "<>", Clue::A_STATUS_UN_ACTION)
                                ->orWhere('crm_status', Clue::CRM_STATUS_REPEAT);
                            break;
                        case "3":
                            $query->where('a_status', Clue::A_STATUS_ARCHIVE_REPEAT)
                                ->orWhere('crm_status', Clue::CRM_STATUS_REPEAT);
                            break;
                    }
                }, '建档状态')->select([
                    '1' => '未建档',
                    '2' => '已建档',
                    '3' => '重复',
                ]);

                $filter->in('user_id')
                    ->multipleSelectTable(DispatchUserTable::make()->payload(['users' => $managerUserId]))
                    ->model(Administrator::class, 'id', 'name');

                $filter->whereBetween('post_date', function ($query) {
                    $start = $this->input['start'] ?? null;
                    $end = $this->input['end'] ?? null;
                    if ($start)
                        $query->where('post_date', ">=", "$start 00:00:00");
                    if ($end)
                        $query->where('post_date', "<=", "$end 23:59:59");
                })->date();

            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Clue(), function (Show $show) {
            $show->field('id');
            $show->field('name');
            $show->field('phone');
            $show->field('source');
            $show->field('url');
            $show->field('site_name');
            $show->field('ad_name');
            $show->field('ad_id');
            $show->field('remark');
            $show->field('ip');
            $show->field('type');
            $show->field('location');
            $show->field('question_data');
            $show->field('post_date');
            $show->field('origin_data');
            $show->field('uuid');
            $show->field('dispatch_date');
            $show->field('rule_id');
            $show->field('user_id');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Clue(), function (Form $form) {
            $form->display('id');
            $form->text('name');
            $form->text('phone');
            $form->text('source');
            $form->text('url');
            $form->text('site_name');
            $form->text('ad_name');
            $form->text('ad_id');
            $form->text('remark');
            $form->text('ip');
            $form->text('type');
            $form->text('location');
            $form->text('question_data');
            $form->text('post_date');
            $form->text('origin_data');
            $form->text('uuid');
            $form->text('dispatch_date');
            $form->text('rule_id');
            $form->text('user_id');

            $form->display('created_at');
            $form->display('updated_at');
        });
    }
}
